import { _decorator, Component, Node, sys } from "cc";
import { DEBUG, DEV, PREVIEW } from "cc/env";
import { EncryptUtil } from "../utils/EncryptUtil";
import Logger from "../utils/Logger";
const { ccclass, property } = _decorator;

/**
 * 存储方案
 * 云平台可以从此类进行扩展
 * key 和 value进行加密处理
 */
export class StorageManager {
    private static _instance: StorageManager;
    private _key: string | null = null;
    private _iv: string | null = null;

    static getInstance() {
        if (!this._instance) {
            this._instance = new StorageManager();
        }
        return this._instance;
    }

    /**
     * 初始化密钥
     * @param key aes加密的key
     * @param iv  aes加密的iv
     */
    init(key: string, iv: string) {
        this._key = EncryptUtil.md5(key);
        this._iv = EncryptUtil.md5(iv);
    }

    getItem(key: string) {
        if (!PREVIEW) {
            key = EncryptUtil.md5(key);
        }
        let val = sys.localStorage.getItem(key);
        if (!PREVIEW && this._key && this._iv && val) {
            val = EncryptUtil.aesDecrypt(val, this._key, this._iv);
        }
        return val;
    }

    setItem(key: string, val: any) {
        if (!val) {
            Logger.error("storage %s val is null", key);
            return;
        }
        if (!PREVIEW) {
            key = EncryptUtil.md5(key);
        }
        if (!PREVIEW && this._key && this._iv) {
            val = EncryptUtil.aesEncrypt(val, this._key, this._iv);
        }
        sys.localStorage.setItem(key, val);
    }

    removeItem(key: string) {
        if (!PREVIEW) {
            key = EncryptUtil.md5(key);
        }
        sys.localStorage.removeItem(key);
    }

    /**
     * 清空应用的本地存储
     */
    clear() {
        sys.localStorage.clear();
    }
}
